class socketIo {
	constructor() {
		this.socketTask = null
		this.isSuccess = false
		this.connectNum = 1
		this.timer = null
		this.isClose = false

	}
	/* socketTask */
	connectSocket() {
			let that = this;
			let token = uni.getStorageSync('token') || 'c2FiZXI6c2FiZXJfc2VjcmV0';
			that.socketTask = uni.connectSocket({
				url: `wss://api.imquanzi.com/ws?token=${token}`,
				success(res) {
					console.log('socketTask连接成功');
					that.isSuccess = true;
				},
				fail(err) {
					console.log('报错', err);
				}
			});
			that.socketTask.onOpen(function(res) {
				that.connectNum = 1;
				console.log('socketTask连接已打开！');
				that.isSuccess = true;
				that.heart();
			});
			that.socketTask.onMessage(function(res) {
				console.log('收到服务器内容：' + res.data);
				that.handlerMsg(JSON.parse(res.data)); //这里是对获取到的数据进行操作
			});
			that.socketTask.onError(function(res) {
				console.log('socketTask连接打开失败，请检查！');
				that.isSuccess = false;
				// let numberTime = that.connectNum++;
				// console.log('失败重连' + this.numberTime);
				// if (that.connectNum > 6) {
				// 	uni.showToast({
				// 		title: '失败重连 超过6次 请重新连接websocket'
				// 	});
				// 	that.isClose = true;
				// 	return;
				// }
				// that.connectSocket();
				//进入重新连接
				that.reconnect();
			});
			// // 监听连接关闭 -
			that.socketTask.onClose(e => {
				console.log('socketTask连接关闭！');
				clearInterval(that.timer);
				that.timer = '';
				if (!that.isClose) {
					that.reconnect();
				}
			});
			console.log(that.socketTask, 'socketTask对象');
		},
		//进入重新连接
		reconnect() {
			let that = this;
			console.log('进入断线重连');
			// this.socketTask.close();
			that.socketTask = null;
			that.connectSocket();
		},
		//发送消息
		sendSocketMessage(msg) {
			console.log('发送信息');
			var that = this;
			console.log(msg);
			console.log(that.socketTask, 'that.socketTask');
			// debugger;
			return new Promise((reslove, reject) => {
				that.socketTask.send({
					data: msg,
					success(res) {
						console.log('发送成功');
						console.log(res, '成功的数据');
						reslove(res);
					},
					fail(res) {
						console.log('发送失败');
						console.log(res);
						console.log(res, '失败的数据');
						reject(res);
					}
				});
			});
		},
		handlerMsg(data) {
			console.log(data, '处理后的数据');
			if (data.command === 20) {
				let name = this.from;
				console.log(name, 'name');
				this.talkList = data.data.friends[name];
			}
		},
		//心跳
		heart() {
			let that = this;
			clearInterval(this.timer);
			this.timer = '';
			let userInfo = uni.getStorageSync('userInfo');
			let msg = {
				cmd: 13,
				hbbyte: '-127'
			};
			this.timer = setInterval(() => {
				that.sendSocketMessage(JSON.stringify(msg))
					.then(res => {
						console.log('心跳成功');
					})
					.catch(res => {
						console.log('发送失败');
						console.log(res);
					});
			}, 200000);
		},
}

module.exports = socketIo
